
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace CommonUtils
{
	public class HttpUtils
	{
		private int _timeout = 31000;

		public int Timeout
		{
			get
			{
				return _timeout;
			}
			set
			{
				_timeout = value;
			}
		}

		public string HttpReqJson(Dictionary<string, string> dict)
		{
			ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
			HttpWebRequest wreq = null;
			HttpWebResponse res = null;
			string strRst = "";
			try
			{
				byte[] data = Encoding.UTF8.GetBytes(dict["data"]);
				wreq = (HttpWebRequest)WebRequest.Create(dict["url"]);
				wreq.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
				wreq.Timeout = 3000;
				wreq.ReadWriteTimeout = 3000;
				wreq.Method = "POST";
				wreq.KeepAlive = false;
				wreq.ContentType = "application/json;charset=utf-8";
				wreq.ServicePoint.Expect100Continue = false;
				using (Stream putStream = wreq.GetRequestStream())
				{
					putStream.Write(data, 0, data.Length);
				}
				res = wreq.GetResponse() as HttpWebResponse;
				byte[] by = new byte[800];
				using (Stream stream2 = res.GetResponseStream())
				{
					int size = 1024;
					int read = 0;
					using (MemoryStream ms = new MemoryStream())
					{
						byte[] buffer = new byte[size];
						do
						{
							read = stream2.Read(buffer, 0, size);
							ms.Write(buffer, 0, read);
						}
						while (read > 0);
						by = ms.ToArray();
					}
				}
				strRst = Encoding.UTF8.GetString(by);
			}
			catch (WebException webEx)
			{
				if (webEx.Response != null)
				{
					HttpWebResponse hwr = webEx.Response as HttpWebResponse;
					string exRsp = string.Empty;
					using (Stream stream = hwr.GetResponseStream())
					{
						StreamReader sr = new StreamReader(stream);
						exRsp = sr.ReadToEnd().ToString();
					}
					return exRsp;
				}
				throw webEx;
			}
			catch (Exception ex)
			{
				throw ex;
			}
			finally
			{
				res?.Close();
				wreq?.Abort();
			}
			return strRst;
		}

		public string DoPost(string url, IDictionary<string, string> parameters, string charset)
		{
			HttpWebRequest req = GetWebRequest(url, "POST");
			req.ContentType = "application/x-www-form-urlencoded;charset=" + charset;
			byte[] postData = Encoding.GetEncoding(charset).GetBytes(BuildQuery(parameters, charset));
			Stream reqStream = req.GetRequestStream();
			reqStream.Write(postData, 0, postData.Length);
			reqStream.Close();
			HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
			Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
			return GetResponseAsString(rsp, encoding);
		}

		public HttpWebRequest GetWebRequest(string url, string method)
		{
			HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
			req.ServicePoint.Expect100Continue = false;
			req.Method = method;
			req.KeepAlive = false;
			req.UserAgent = "Aop4Net";
			req.Timeout = _timeout;
			req.ReadWriteTimeout = _timeout;
			return req;
		}

		public string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
		{
			StringBuilder result = new StringBuilder();
			Stream stream = null;
			StreamReader reader = null;
			try
			{
				stream = rsp.GetResponseStream();
				reader = new StreamReader(stream, encoding);
				int ch = -1;
				while ((ch = reader.Read()) > -1)
				{
					char c = (char)ch;
					if (c != 0)
					{
						result.Append(c);
					}
				}
			}
			finally
			{
				reader?.Close();
				stream?.Close();
				rsp?.Close();
			}
			return result.ToString();
		}

		public static string BuildQuery(IDictionary<string, string> parameters, string charset)
		{
			StringBuilder postData = new StringBuilder();
			bool hasParam = false;
			IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
			while (dem.MoveNext())
			{
				string name = dem.Current.Key;
				string value = dem.Current.Value;
				if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
				{
					if (hasParam)
					{
						postData.Append("&");
					}
					postData.Append(name);
					postData.Append("=");
					string encodedValue = HttpUtility.UrlEncode(value, Encoding.GetEncoding(charset));
					postData.Append(encodedValue);
					hasParam = true;
				}
			}
			return postData.ToString();
		}
	}
}
